package com.solution.action;

import java.io.IOException;
import java.rmi.RemoteException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.solution.constant.LoginConstants;
import com.solution.constant.StatusConstants;
import com.solution.delegate.ExaminationServiceDelegate;
import com.solution.delegate.UserInfoServiceDelegate;
import com.solution.exception.DelegateException;
import com.solution.exception.ServiceBeanException;
import com.solution.form.ExamForm;
import com.solution.model.CategoryType;
import com.solution.model.ExamCategoryLevelMapping;
import com.solution.model.ExamCategoryLevelMappingId;
import com.solution.model.ExamType;
import com.solution.model.LevelType;
import com.solution.model.QuestionType;
import com.solution.model.UserInfo;
import com.solution.util.SearchVO;
import com.solution.webconstant.ExaminationConstant;

public class ExamAction extends Action{

	/**
	 * logging instance.
	 */
	private Logger logger = Logger.getLogger(ExamAction.class.getName());

	/**
	 * Default method.
	 */
	public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		logger.debug("Entering :: ExamAction:execute()");
		ExamForm examForm =(ExamForm)form;
		request.setAttribute("tab", "EXAM");
		request.setAttribute("editLink", "/searchExam.do?screen_type=Edit");
		request.setAttribute("viewLink", "/searchExam.do?screen_type=View");
		request.setAttribute("createLink", "/exam.do");
		
		ActionMessages  errors  = new ActionMessages();
		HttpSession session = request.getSession();
		try{
			UserInfo userInfo = (UserInfo)request.getSession().getAttribute(LoginConstants.SESSION_USER_INFO);
			Integer activeExams = 0;
			Integer inActiveExams = 0;
			String latestExam = "None";
			ExaminationServiceDelegate examinationServiceDelegate = new ExaminationServiceDelegate();
			SearchVO searchVO = new SearchVO();
			searchVO.addEqualsCondition("status", StatusConstants.ACTIVE);
			searchVO.addEqualsCondition("clientType.id", userInfo.getClientType().getId(), true);
			activeExams = examinationServiceDelegate.countExams(searchVO);
			
			searchVO.clear();
			searchVO.addEqualsCondition("status", StatusConstants.SUSPEND);
			searchVO.addEqualsCondition("clientType.id", userInfo.getClientType().getId(), true);
			inActiveExams = examinationServiceDelegate.countExams(searchVO);
			
			searchVO.clear();
			searchVO.addOrderDescending("createdOn");
			searchVO.addEqualsCondition("clientType.id", userInfo.getClientType().getId(), true);
			searchVO.setPageNumber(1);
			searchVO.setPageSize(1);
			List<ExamType> exams = examinationServiceDelegate.fetchExams(searchVO);
			if(exams != null && exams.size()>0){
				latestExam = exams.get(0).getName();
			}
			session.setAttribute("LatestExam", latestExam);
			session.setAttribute("ActiveExam", activeExams);
			session.setAttribute("InactiveExam", inActiveExams);
			
		}
		catch(ServiceBeanException sbe){
			logger.error(sbe);
			errors.add("error", new ActionMessage("Exam.fail.exception", sbe.getMessage()));
			examForm.setScreen_type("");
		}
		catch(DelegateException de){
			logger.error(de);
			errors.add("error", new ActionMessage("Exam.add.fail"));
			examForm.setScreen_type("");
		}
		saveErrors(request, errors);
		
		/**
		 * Creation Case.
		 */
		if("/createExam".equals(mapping.getPath())){
			request.setAttribute("selectedTab", "create");
			return createExam(mapping, examForm, request, response);
		}
		/**
		 * Search Case.
		 */
		else if("/searchExam".equals(mapping.getPath())){
			if("Edit".equalsIgnoreCase(examForm.getScreen_type())){
				request.setAttribute("selectedTab", "edit");
			}else if("View".equalsIgnoreCase(examForm.getScreen_type())){
				request.setAttribute("selectedTab", "view");
			}
			return searchExam(mapping, examForm, request, response);
		}
		/**
		 * Updation Case.
		 */
		else if("/updateExam".equals(mapping.getPath())){
			if("Edit".equalsIgnoreCase(examForm.getScreen_type())){
				request.setAttribute("selectedTab", "edit");
			}else if("View".equalsIgnoreCase(examForm.getScreen_type())){
				request.setAttribute("selectedTab", "view");
			}
			return updateExam(mapping, examForm, request, response);
		}
		/**
		 * Edit/View Case.
		 */
		else if("/editViewExam".equals(mapping.getPath())){
			if("Edit".equalsIgnoreCase(examForm.getScreen_type())){
				request.setAttribute("selectedTab", "edit");
			}else if("View".equalsIgnoreCase(examForm.getScreen_type())){
				request.setAttribute("selectedTab", "view");
			}
			return editViewExam(mapping, examForm, request, response);
		}
		else if("/availableQuestions".equals(mapping.getPath())){
			return availableQuestions(mapping, examForm, request, response);
		}else if("/isExamNameExist".equals(mapping.getPath())){
			return isExamNameExist(mapping, examForm, request, response);
		}		
		else{
			request.setAttribute("selectedTab", "create");
			return fetchCategoryLevelList(mapping, examForm, request, response);
		}
	}
	
	public ActionForward isExamNameExist(ActionMapping mapping,ExamForm examForm,HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		try{
			UserInfo userInfo = (UserInfo)request.getSession().getAttribute(LoginConstants.SESSION_USER_INFO);
			ExaminationServiceDelegate examinationServiceDelegate = new ExaminationServiceDelegate();
			SearchVO searchVO = new SearchVO();
			searchVO.addEqualsCondition("name", examForm.getExam_name());
			searchVO.addEqualsCondition("clientType.id", userInfo.getClientType().getId(), true);
			List<ExamType> examTypeList = examinationServiceDelegate.fetchExams(searchVO);
			if(examTypeList!= null && examTypeList.size()>0){
				response.getWriter().write("TRUE");
			}else{
				response.getWriter().write("");
			}
		}
		catch(ServiceBeanException sbe){
			logger.error(sbe);			
		}
		catch(DelegateException de){
			logger.error(de);			
		}		
		return null;
		
	}
	
	public ActionForward availableQuestions(ActionMapping mapping,ExamForm examForm,HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		try{
			UserInfo userInfo = (UserInfo)request.getSession().getAttribute(LoginConstants.SESSION_USER_INFO);
			ExaminationServiceDelegate examinationServiceDelegate = new ExaminationServiceDelegate();
			SearchVO searchVO = new SearchVO();
			searchVO.addEqualsCondition("categoryType", examinationServiceDelegate.getCategory(examForm.getCategory_id()));
			searchVO.addEqualsCondition("levelType", examinationServiceDelegate.getLevel(examForm.getLevel_id()));
			searchVO.addEqualsCondition("status", StatusConstants.ACTIVE);
			searchVO.addEqualsCondition("clientType.id", userInfo.getClientType().getId(), true);
			if(examForm.getMultiple_choice_enable()==0){
				searchVO.addEqualsCondition("correctOptionsCount", 1);
			}
//			else{
//				searchVO.addGreaterCondition("correctOptionsCount", 1);
//			}
			List<QuestionType> questionList = examinationServiceDelegate.fetchQuestions(searchVO);
			if(questionList!= null && questionList.size()>0){
				response.getWriter().write(String.valueOf(questionList.size()));
			}else{
				response.getWriter().write("0");
			}
		}
		catch(ServiceBeanException sbe){
			logger.error(sbe);			
		}
		catch(DelegateException de){
			logger.error(de);			
		}		
		return null;
		
	}

	public ActionForward fetchCategoryLevelList(ActionMapping mapping,ExamForm examForm,HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		ActionMessages  errors  = new ActionMessages() ;
		try{
			UserInfo userInfo = (UserInfo)request.getSession().getAttribute(LoginConstants.SESSION_USER_INFO);
			ExaminationServiceDelegate examinationServiceDelegate = new ExaminationServiceDelegate();
			List<CategoryType> categories = examinationServiceDelegate.fetchActiveCategories(userInfo.getClientType().getId());
			if(categories != null && categories.size()>0){
				examForm.setCategories(categories);
			}
			List<LevelType> levels = examinationServiceDelegate.fetchActiveLevels(userInfo.getClientType().getId());
			if(levels != null && levels.size() >0){
				examForm.setLevels(levels);
			}
		}
		catch(ServiceBeanException sbe){
			logger.error(sbe);
			errors.add("error", new ActionMessage("Exam.fail.exception", sbe.getMessage()));
    		examForm.setScreen_type("");
		}
		catch(DelegateException de){
			logger.error(de);
			errors.add("error", new ActionMessage("Exam.add.fail"));
			examForm.setScreen_type("");
		}
		return mapping.findForward("init");
	}
	
	public ActionForward createExam(ActionMapping mapping,ExamForm examForm,HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		logger.debug("Entering :: ExamAction:createExam()");
		ActionMessages messages = new ActionMessages();
		ActionMessages  errors  = new ActionMessages() ;
		ExamType exam=null;
		try{
			UserInfo userInfo = (UserInfo)request.getSession().getAttribute(LoginConstants.SESSION_USER_INFO);
			ActionMessages guiErrors = examForm.validate(mapping, request);
			ExaminationServiceDelegate examinationServiceDelegate = new ExaminationServiceDelegate();
			if(guiErrors!=null && guiErrors.size()>0){
	    		saveErrors(request, guiErrors);
				List<CategoryType> categories = examinationServiceDelegate.fetchActiveCategories(userInfo.getClientType().getId());
				if(categories != null && categories.size()>0){
					examForm.setCategories(categories);
				}
				List<LevelType> levels = examinationServiceDelegate.fetchActiveLevels(userInfo.getClientType().getId());
				if(levels != null && levels.size() >0){
					examForm.setLevels(levels);
				}
				examForm.setScreen_type("");
	    		return mapping.findForward("createExam");
	    	}
			// obtain the PO.
			exam = convertFormToPersistentObject(examForm,request,"add");
			// create the entity in database.
			List<ExamCategoryLevelMapping> questionTypes= new ArrayList<ExamCategoryLevelMapping>();
			ExamCategoryLevelMapping examCategoryLevelMapping = null;
			for(int i=0;i< examForm.getQuestion_category_id().length;i++)
			{
				examCategoryLevelMapping = new ExamCategoryLevelMapping();
				ExamCategoryLevelMappingId examCategoryLevelMappingId = new ExamCategoryLevelMappingId();
				CategoryType categoryType = examinationServiceDelegate.getCategory(Long.parseLong(examForm.getQuestion_category_id()[i]));
				LevelType levelType = examinationServiceDelegate.getLevel(Long.parseLong(examForm.getQuestion_level_id()[i]));
				examCategoryLevelMapping.setCategoryType(categoryType);
				examCategoryLevelMapping.setLevelType(levelType);
				examCategoryLevelMapping.setNumberQuestions(examForm.getQuestion_count()[i]);
				examCategoryLevelMappingId.setCategoryTypeId(categoryType.getId());
				examCategoryLevelMappingId.setLevelTypeId(levelType.getId());
				examCategoryLevelMapping.setId(examCategoryLevelMappingId);
				questionTypes.add(examCategoryLevelMapping);
				
			}
			exam = examinationServiceDelegate.createExam(exam, questionTypes);
			if(exam != null){
				messages.add("message", new ActionMessage("Exam.add.success"));
				saveMessages(request, messages);
				// set the form parameters for the next navigation.
				if(exam.getId() != null){
					examForm.setExam_id(exam.getId().longValue()+"");
				}
				List<CategoryType> categories = examinationServiceDelegate.fetchActiveCategories(userInfo.getClientType().getId());
				if(categories != null && categories.size()>0){
					examForm.setCategories(categories);
				}
				List<LevelType> levels = examinationServiceDelegate.fetchActiveLevels(userInfo.getClientType().getId());
				if(levels != null && levels.size() >0){
					examForm.setLevels(levels);
				}
				SearchVO searchVO = new SearchVO();
				searchVO.addEqualsCondition("examType", exam);
				List<ExamCategoryLevelMapping> examCategoryLevelMappingList = examinationServiceDelegate.fetchExamCategoryLevelMapping(searchVO);
				examForm.setExamCategoryLevelMappingList(examCategoryLevelMappingList);
				examForm.setScreen_type(ExaminationConstant.SCREEN_TYPE_VIEW);
			}
			else{
				errors.add("error", new ActionMessage("Exam.add.fail"));
				examForm.setScreen_type("");
			}
		}
		catch(RemoteException re){
			logger.error(re);
			errors.add("error", new ActionMessage("Exam.add.fail"));
			examForm.setScreen_type("");
		}
		catch(ServiceBeanException sbe){
			logger.error(sbe);
			errors.add("error", new ActionMessage("Exam.fail.exception", sbe.getMessage()));
			examForm.setScreen_type("");
		}
		catch(DelegateException de){
			logger.error(de);
			errors.add("error", new ActionMessage("Exam.add.fail"));
			examForm.setScreen_type("");
		}
		catch(ParseException pe){
			logger.error(pe);
			errors.add("error", new ActionMessage("Exam.add.fail"));
			examForm.setScreen_type("");
		}
		saveErrors(request, errors);
		logger.debug("Exiting :: ExamAction:createExam()");
		return mapping.findForward("createExam");
	}

	public ActionForward searchExam(ActionMapping mapping,ExamForm examForm,HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		logger.debug("Entering :: ExamAction:searchExam()");
		ActionMessages errors  = new ActionMessages();
		try{
			UserInfo userInfo = (UserInfo)request.getSession().getAttribute(LoginConstants.SESSION_USER_INFO);
			ExaminationServiceDelegate examinationServiceDelegate = new ExaminationServiceDelegate();
			if(examForm.getShow_list() == null || examForm.getShow_list().equals("")){
				examForm.setShow_list("N");
			}
			else{
				ActionMessages guiErrors = examForm.validate(mapping, request);
				if(guiErrors!=null && guiErrors.size()>0){
		    		saveErrors(request, guiErrors);
		    		List<CategoryType> categories = examinationServiceDelegate.fetchActiveCategories(userInfo.getClientType().getId());
					if(categories != null && categories.size()>0){
						examForm.setCategories(categories);
					}
					List<LevelType> levels = examinationServiceDelegate.fetchActiveLevels(userInfo.getClientType().getId());
					if(levels != null && levels.size() >0){
						examForm.setLevels(levels);
					}
					examForm.setShow_list("N");
		    		return mapping.findForward("searchExam");
		    	}
				// filling the search criteria.
				SearchVO searchVO = new SearchVO();
				List<ExamType> examList = null;
				searchVO.addEqualsCondition("clientType.id", userInfo.getClientType().getId(), true);
				if(examForm.getExam_name()!= null && !examForm.getExam_name().equals("")){
					searchVO.addLikeIgnoreCaseCondition("name", examForm.getExam_name());
				}
				if(examForm.getStatus() != null && !examForm.getStatus().equals("")){
					searchVO.addEqualsCondition("status", new Short(examForm.getStatus()));
				}
				if(examForm.getExam_time_hr() != null && !examForm.getExam_time_hr().equals("") && 
					examForm.getExam_time_min() != null && !examForm.getExam_time_min().equals("")){
					Long sec = Long.parseLong(examForm.getExam_time_hr())*3600;
					sec = sec + Long.parseLong(examForm.getExam_time_min())*60;
					searchVO.addEqualsCondition("time", sec);
				}
				if(examForm.getNegative_enable() != null && !examForm.getNegative_enable().equals("")){
					searchVO.addEqualsCondition("negativeEnabled", new Short(examForm.getNegative_enable()));
				}
				if(examForm.getMultiple_choice_enable() != null && !examForm.getMultiple_choice_enable().equals("")){
					searchVO.addEqualsCondition("multipleChoiceEnabled", new Short(examForm.getMultiple_choice_enable()));
				}
				if(examForm.getExam_create_from() != null && !examForm.getExam_create_from().equals("")){
					searchVO.addGreaterEqualsCondition("createdOn", new java.text.SimpleDateFormat("MM/dd/yyyy").parse(examForm.getExam_create_from()));
				}
				if(examForm.getExam_create_to() != null && !examForm.getExam_create_to().equals("")){
					searchVO.addLesserEqualsCondition("createdOn", new java.text.SimpleDateFormat("MM/dd/yyyy").parse(examForm.getExam_create_to()));
				}
				examList = examinationServiceDelegate.fetchExams(searchVO);
				examForm.setShow_list("Y");
				if(examList!=null && examList.size()>0){
					examForm.setExam_list(examList);
				}
				else{
					errors.add("error", new ActionMessage("Exam.search.fail"));
				}
			}
			List<CategoryType> categories = examinationServiceDelegate.fetchActiveCategories(userInfo.getClientType().getId());
			if(categories != null && categories.size()>0){
				examForm.setCategories(categories);
			}
			List<LevelType> levels = examinationServiceDelegate.fetchActiveLevels(userInfo.getClientType().getId());
			if(levels != null && levels.size() >0){
				examForm.setLevels(levels);
			}
		}
		catch(ServiceBeanException sbe){
			logger.error(sbe);
			errors.add("error", new ActionMessage("Exam.fail.exception", sbe.getMessage()));
		}
		catch(DelegateException de){
			logger.error(de);
			errors.add("error", new ActionMessage("Exam.search.fail"));
		}
		catch(ParseException pe){
			logger.error(pe);
			errors.add("error", new ActionMessage("Exam.search.fail"));
		}
		saveErrors(request, errors);
		logger.debug("Exiting :: ExamAction:searchExam()");
		return mapping.findForward("searchExam");
	}

	public ActionForward updateExam(ActionMapping mapping,ExamForm examForm,HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		logger.debug("Entering :: ExamAction:updateExam()");
		ActionMessages messages = new ActionMessages();
		ActionMessages errors  = new ActionMessages() ;
		ExamType exam =null;
		try{
			UserInfo userInfo = (UserInfo)request.getSession().getAttribute(LoginConstants.SESSION_USER_INFO);
			ActionMessages guiErrors = examForm.validate(mapping, request);
			ExaminationServiceDelegate examinationServiceDelegate = new ExaminationServiceDelegate();
			if(guiErrors!=null && guiErrors.size()>0){
	    		saveErrors(request, guiErrors);
	    		List<CategoryType> categories = examinationServiceDelegate.fetchActiveCategories(userInfo.getClientType().getId());
				if(categories != null && categories.size()>0){
					examForm.setCategories(categories);
				}
				List<LevelType> levels = examinationServiceDelegate.fetchActiveLevels(userInfo.getClientType().getId());
				if(levels != null && levels.size() >0){
					examForm.setLevels(levels);
				}
	    		examForm.setScreen_type(ExaminationConstant.SCREEN_TYPE_EDIT);
	    		return mapping.findForward("updateExam");
	    	}
			
			exam = convertFormToPersistentObject(examForm,request,"edit");
			List<ExamCategoryLevelMapping> questionTypes= new ArrayList<ExamCategoryLevelMapping>();
			ExamCategoryLevelMapping examCategoryLevelMapping = null;
			for(int i=0;i< examForm.getQuestion_category_id().length;i++)
			{
				examCategoryLevelMapping = new ExamCategoryLevelMapping();
				ExamCategoryLevelMappingId examCategoryLevelMappingId = new ExamCategoryLevelMappingId();
				CategoryType categoryType = examinationServiceDelegate.getCategory(Long.parseLong(examForm.getQuestion_category_id()[i]));
				LevelType levelType = examinationServiceDelegate.getLevel(Long.parseLong(examForm.getQuestion_level_id()[i]));
				examCategoryLevelMapping.setCategoryType(categoryType);
				examCategoryLevelMapping.setLevelType(levelType);
				examCategoryLevelMapping.setNumberQuestions(examForm.getQuestion_count()[i]);
				examCategoryLevelMappingId.setCategoryTypeId(categoryType.getId());
				examCategoryLevelMappingId.setLevelTypeId(levelType.getId());
				examCategoryLevelMapping.setId(examCategoryLevelMappingId);
				questionTypes.add(examCategoryLevelMapping);
				
			}
			exam = examinationServiceDelegate.updateExam(exam, questionTypes);
			if(exam != null){
				messages.add("message", new ActionMessage("Exam.update.success"));
				saveMessages(request, messages);
				// set the form parameters for the next navigation.
				if(exam.getId() != null){
					examForm.setExam_id(exam.getId().longValue()+"");
				}
				List<CategoryType> categories = examinationServiceDelegate.fetchActiveCategories(userInfo.getClientType().getId());
				if(categories != null && categories.size()>0){
					examForm.setCategories(categories);
				}
				List<LevelType> levels = examinationServiceDelegate.fetchActiveLevels(userInfo.getClientType().getId());
				if(levels != null && levels.size() >0){
					examForm.setLevels(levels);
				}
				SearchVO searchVO = new SearchVO();
				searchVO.addEqualsCondition("examType", exam);
				List<ExamCategoryLevelMapping> examCategoryLevelMappingList = examinationServiceDelegate.fetchExamCategoryLevelMapping(searchVO);
				examForm.setExamCategoryLevelMappingList(examCategoryLevelMappingList);
				examForm.setScreen_type(ExaminationConstant.SCREEN_TYPE_VIEW);
			}
			else{
				errors.add("error", new ActionMessage("Exam.update.fail"));
				examForm.setScreen_type(ExaminationConstant.SCREEN_TYPE_EDIT);
			}
		}
		catch(RemoteException re){
			logger.error(re);
			errors.add("error", new ActionMessage("Exam.update.fail"));
			examForm.setScreen_type(ExaminationConstant.SCREEN_TYPE_EDIT);
		}
		catch(ServiceBeanException sbe){
			logger.error(sbe);
			errors.add("error", new ActionMessage("Exam.fail.exception", sbe.getMessage()));
			examForm.setScreen_type(ExaminationConstant.SCREEN_TYPE_EDIT);
		}
		catch(DelegateException de){
			logger.error(de);
			errors.add("error", new ActionMessage("Exam.update.fail"));
			examForm.setScreen_type(ExaminationConstant.SCREEN_TYPE_EDIT);
		}
		catch(ParseException pe){
			logger.error(pe);
			errors.add("error", new ActionMessage("Exam.add.fail"));
			examForm.setScreen_type(ExaminationConstant.SCREEN_TYPE_EDIT);
		}
		saveErrors(request, errors);
		logger.debug("Exiting :: ExamAction:updateExam()");
		return mapping.findForward("updateExam");
	}

	public ActionForward editViewExam(ActionMapping mapping,ExamForm examForm,HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		logger.debug("Entering :: ExamAction:editViewExam()");
		ActionMessages errors  = new ActionErrors() ;
		try{
			UserInfo userInfo = (UserInfo)request.getSession().getAttribute(LoginConstants.SESSION_USER_INFO);
			if(examForm.getExam_id() != null && !examForm.getExam_id().equals("")){
				ExaminationServiceDelegate examinationServiceDelegate = new ExaminationServiceDelegate();
				UserInfoServiceDelegate userService = new UserInfoServiceDelegate();
				Long examId = new Long(examForm.getExam_id());
				ExamType exam =examinationServiceDelegate.getExam(examId);
				//fill the form for displaying the details.
				if(exam != null){
					examForm.setExam_name(exam.getName());
					examForm.setExam_description(exam.getDescription());
					examForm.setNegative_enable(exam.getNegativeEnabled());
					examForm.setMultiple_choice_enable(exam.getMultipleChoiceEnabled());
					examForm.setTotalMarks(exam.getMaximumMarks());
					int seconds = exam.getTime().intValue();
					int hrs = seconds/3600;
					int sec = seconds%3600;
					examForm.setExam_time_hr(hrs+"");
					examForm.setExam_time_min(sec/60+"");
					if(exam.getStatus() != null){
						examForm.setStatus(exam.getStatus().shortValue()+"");
					}
					if(exam.getPassingMarks() != null){
						examForm.setPassing_marks(exam.getPassingMarks().longValue()+"");
					}
					List<CategoryType> categories = examinationServiceDelegate.fetchActiveCategories(userInfo.getClientType().getId());
					SearchVO searchVO = new SearchVO();
					searchVO.addEqualsCondition("examType", exam);
					List<ExamCategoryLevelMapping> examCategoryLevelMappingList = examinationServiceDelegate.fetchExamCategoryLevelMapping(searchVO);
					examForm.setExamCategoryLevelMappingList(examCategoryLevelMappingList);
					
					searchVO.clear();
					searchVO.addEqualsCondition("examType.id", examId,true);
					searchVO.addEqualsCondition("status", LoginConstants.USER_BLOCKED);
					List<UserInfo> userInfoList = userService.searchUser(searchVO);
					if(userInfoList!= null && userInfoList.size()>0){
						examForm.setIs_updatable(false);
					}else{
						examForm.setIs_updatable(true);
					}
					searchVO.clear();
					searchVO.addEqualsCondition("examType.id", examId,true);
					userInfoList = userService.searchUser(searchVO);
					if(userInfoList!= null && userInfoList.size()>0){
						examForm.setCanShowChart(true);
					}else{
						examForm.setCanShowChart(false);
					}
					if(categories != null && categories.size()>0){
						examForm.setCategories(categories);
					}
					List<LevelType> levels = examinationServiceDelegate.fetchActiveLevels(userInfo.getClientType().getId());
					if(levels != null && levels.size() >0){
						examForm.setLevels(levels);
					}
				}
				else{
					errors.add("error", new ActionMessage("Exam.details.fail"));
				}
			}
			else{
				errors.add("error", new ActionMessage("Exam.details.fail"));
			}
		}
		catch(ServiceBeanException sbe){
			logger.error(sbe);
			errors.add("error", new ActionMessage("Exam.fail.exception", sbe.getMessage()));
		}
		catch(DelegateException de){
			logger.error(de);
			errors.add("error", new ActionMessage("Exam.details.fail"));
		}
		saveErrors(request, errors);
		logger.debug("Exiting :: ExamAction:editViewExam()");
		return mapping.findForward("editViewExam");
	}

	private ExamType convertFormToPersistentObject(ExamForm examForm,
			HttpServletRequest request,String pageType) throws ServiceBeanException, DelegateException, IOException, ParseException {
		logger.debug("Entering :: ExamAction:convertFormToPersistentObject()");
		HttpSession session = request.getSession();
		UserInfo userInfo = null;
		if(session != null){
			userInfo = (UserInfo)session.getAttribute(LoginConstants.SESSION_USER_INFO);
		}
		// Creation case.
		ExamType exam = new ExamType();
		// modification case.
		if("edit".equalsIgnoreCase(pageType)){
			logger.info("Update case for the exam :"+examForm.getExam_id());
			ExaminationServiceDelegate examinationServiceDelegate = new ExaminationServiceDelegate();
			exam = examinationServiceDelegate.getExam(new Long(examForm.getExam_id().trim()));
		}
	    // filling the persistent object.
		exam.setDescription(examForm.getExam_description());
		exam.setNegativeEnabled((Short)examForm.getNegative_enable());
		if(examForm.getStatus() != null && !examForm.getStatus().trim().equals("")){
			exam.setStatus(new Short(examForm.getStatus().trim()));
		}
		if(examForm.getPassing_marks() != null && !examForm.getPassing_marks().trim().equals("")){
			exam.setPassingMarks(new Long(examForm.getPassing_marks().trim()));
		}
		if(examForm.getMultiple_choice_enable() != null ){
			exam.setMultipleChoiceEnabled(examForm.getMultiple_choice_enable());
		}
		exam.setMaximumMarks(examForm.getTotalMarks());
	    // creation case.
		if("add".equalsIgnoreCase(pageType)){
			exam.setName(examForm.getExam_name().trim());
			if(userInfo != null){
				exam.setCreatedBy(userInfo.getUsername());
			}
			exam.setCreatedOn(new Date());
			Long sec = Long.parseLong(examForm.getExam_time_hr())*3600;
			sec = sec + Long.parseLong(examForm.getExam_time_min())*60;
			exam.setTime(sec);
			exam.setClientType(userInfo.getClientType());
		}
		// modification case.
		else{
			if(userInfo != null){
				exam.setModifiedBy(userInfo.getUsername());
			}
			exam.setModifiedOn(new Date());
		}
		logger.debug("Exiting :: ExamAction:convertFormToPersistentObject()");
		return exam;
	}
}
